import machine, onewire, ds18x20, time
from lib.config.index import sensor_config

"""
ds18b20温度传感器
"""


def demo():
    ds18b20_config = sensor_config.get_sensor("ds18b20")

    if not ds18b20_config:
        return

    # print(ds18b20_config)

    pin_num = ds18b20_config["pin"]
    ds_pin = machine.Pin(pin_num)
    ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))

    roms = ds_sensor.scan()
    print("Found DS devices: ", roms)

    while True:
        ds_sensor.convert_temp()
        time.sleep_ms(750)
        for rom in roms:
            print(rom)
            tempC = ds_sensor.read_temp(rom)
            tempF = tempC * (9 / 5) + 32
            print("temperature (ºC):", "{:.2f}".format(tempC))
            print("temperature (ºF):", "{:.2f}".format(tempF))
            print()
        time.sleep(5)


def init_ds18b20(pin_num):
    ds_pin = machine.Pin(pin_num)
    ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))
    roms = ds_sensor.scan()
    print("Found DS devices: ", roms)


if __name__ == "__main__":
    demo()
